import { getButtons, getInfo, login, logout } from '@/api/login'
import { getToken, removeToken, setToken } from '@/utils/auth'

const user = {
    state: {
        token: getToken(),
        name: '',
        avatar: '',
        buttons: []
    },

    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_BUTTONS: (state, buttons) => {
            state.buttons = buttons
        }
    },

    actions: {
        // 登录
        Login({ commit }, userInfo) {
            const username = userInfo.username.trim()
            return new Promise((resolve, reject) => {
                login(username, userInfo.password).then(response => {
                    const data = response.data
                    setToken(data)
                    commit('SET_TOKEN', data)
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        async GetInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                getInfo().then(response => {
                    const user = response.data
                    commit('SET_NAME', user.name)
                    commit('SET_AVATAR', user.avatar)
                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        async GetButtons({ commit, state }) {
            return new Promise((resolve, reject) => {
                getButtons().then((response) => {
                    const buttonAuthList = []
                    response.data.forEach(button => {
                        buttonAuthList.push(button)
                    })
                    commit('SET_BUTTONS', buttonAuthList)
                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        //退出登录,请求后端接口
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(() => {
                    commit('SET_TOKEN', '')// 清空前端vuex中存储的数据
                    commit('SET_BUTTONS', [])//清空按钮权限
                    removeToken()// 清空cookie
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 前端 登出
        FedLogOut({ commit }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        }
    }
}

export default user
